import React from 'react';
import ReactDom from 'react-dom';
import {
    Form,
    Input,
    Select,
    Cascader,
    Row,
    Col,
    Checkbox,
    Button,
    Modal,
    Table,
    Pagination,
    Radio,
    Icon,
    Collapse,
    message
} from 'antd';
import {Search, UserForm, SetRole, SetPwd, AddForm, OrgTree, OrgTreeSelect} from './components/form';
import filter from 'filter';
import util from 'util';
import {RightButton,SearchDemo} from 'kpl'

const confirm = Modal.confirm;

class User extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            addVisible: false,
            roleVisible: false,
            pwdVisible: false,
            dataSource: [],
            orgno: "",
            index: 0,
            operation: "",
            userstatus: "",
            add: false,
            edit: false,
            setting: false,
            setPwd: false,
            switchUserStatus: false,
            modifyData: {},
            randomKey: "123",
            loading: false,
            current: 1,
            pageSize: 10,
            total: "",
            userid: "",
            searchParams: {
                username: "",
                loginname: "",
                userstatus: "",
                usertype: "",
                orgno: ""
            },
            checkedValues: []
        };
        this.willUnmount = true;
        this.rights = [];
        this.searchParams = {};

    }

    componentWillUnmount() {
        this.willUnmount = false;
    }

    componentDidMount() {


        this.rights = util.checkRights(["512", "513", "514", "515"]);
        //初始化用户信息2143
        var orgno = util.getLocalObj("userInfo").orgno;
        var orgid = util.getLocalObj("userInfo").orgid;
        var orgname = util.getLocalObj("userInfo").orgname;
        this.setState({orgno, orgid, orgname});
        console.log("***********************888888888888888****", util.getLocalObj("userInfo"));
        util.httpRequest({
            type: "POST",
            url: 'user020101.json',
            params: {page: "1", rows: "10", orgno: orgno, orgid: orgid},
            //params: {page: "1", rows: "10", orgno: "0200"},
            success: function (result) {
                console.log(result);
                this.setState({
                    dataSource: result.rows,
                    total: result.total
                })
            }.bind(this)
        });
        //设置按钮权限
        var oprates = util.getLocalObj("roleids");
        if (oprates[0] == "SYSTEM") {
            this.setState({
                add: true,
                edit: true,
                setting: true,
                setPwd: true,
                switchUserStatus: true
            });
        } else {
            for (var i = 0; i < oprates.length; i++) {
                switch (oprates[i]) {
                    case "511":
                        this.setState({
                            add: true
                        });
                        break;
                    case "512":
                        this.setState({
                            edit: true
                        });
                        break;
                    case "513":
                        this.setState({
                            setting: true
                        });
                        break;
                    case "514":
                        this.setState({
                            setPwd: true
                        });
                        break;
                    case "515":
                        this.setState({
                            switchUserStatus: true
                        });
                        break;
                }
            }
        }
        console.log(this.state);
    }

    refresh(current, pageSize) {


        this.setState({
            loading: true
        })
        if (this.state.orgno) {
            var orgno = this.state.orgno;
        } else {
            var orgno = util.getLocalObj("userInfo").orgno;

        }

        this.searchParams.page = current;
        this.searchParams.pageSize = pageSize;
        this.searchParams.rows = pageSize;
        this.searchParams.orgno = orgno;
        //刷新用户信息
        util.httpRequest({
            type: "POST",
            url: 'user020101.json',
            //params: {page: current, rows: pageSize, orgno: orgno},
            params: this.searchParams,
            success: function (result) {
                console.log(result);
                this.setState({
                    dataSource: result.rows
                })
            }.bind(this),
            complete: function () {
                if (this.willUnmount) {
                    this.setState({
                        loading: false
                    })
                }
            }.bind(this)
        });
    }

    modify(data, index) {
        this.show(data, index, "modify");
    }

    remove(index) {
        var dataSource = this.state.dataSource;

        dataSource.splice(index, 1);

        this.setState({
            dataSource: dataSource
        })
    }

    setRole(data, index) {
        this.roleShow(data, index);
    }

    setPwd(data, index) {
        this.pwdShow(data, index);

    }

    add(data, index) {
        this.show(data, index, "add");
    }

    switchStatus(data, index) {
        var me = this;
        if (data.userstatus == "F") {
            confirm({
                title: '系统提示',
                content: '确认启用用户账户吗？',
                onOk() {
                    var dataSource = me.state.dataSource;
                    dataSource[index].userstatus = "N";
                    util.httpRequest({
                        type: "POST",
                        url: 'user020105.json',
                        params: {userstatus: dataSource[index].userstatus, userid: dataSource[index].userid},
                        success: function (result) {
                            console.log(result);
                            if (result.ret_code == "0000") {
                                me.setState({
                                    dataSource: dataSource
                                });
                                message.success('启用成功！');
                                me.refresh(me.state.current, me.state.pageSize);
                            }
                        }.bind(this)
                    });
                },
                onCancel() {
                }
            })
        } else {
            confirm({
                title: '系统提示',
                content: '确认停用用户账户吗？',
                onOk() {
                    var dataSource = me.state.dataSource;
                    dataSource[index].userstatus = "F";
                    util.httpRequest({
                        type: "POST",
                        url: 'user020105.json',
                        params: {userstatus: dataSource[index].userstatus, userid: dataSource[index].userid},
                        success: function (result) {
                            console.log(result);
                            if (result.ret_code == "0000") {
                                me.setState({
                                    dataSource: dataSource
                                });
                                message.success('停用成功！');
                                me.refresh(me.state.current, me.state.pageSize);
                            }
                        }.bind(this)
                    });
                },
                onCancel() {
                }
            })
        }
    }

    config() {
        var me = this;


        const columns = [{
            title: '用户类型',
            dataIndex: 'usertype',
            key: 'usertype',
            render: function (value, data, rowIndex) {
                var str = util.convert("usertype", value);
                return str;
            }

        }, {
            title: '登录名称',
            dataIndex: 'loginname',
            key: 'loginname'
        }, {
            title: '用户名称',
            dataIndex: 'username',
            key: 'username'
        }, {
            title: '用户状态',
            dataIndex: 'userstatus',
            key: 'userstatus',
            render: function (value) {
                var str = util.convert("userstatus", value);
                return str;
            }
        }, {
            title: '所属机构',
            dataIndex: 'orgname',
            key: 'orgname'
        }, {
            title: '用户操作',
            key: 'operation',
            render: (text, data, index) => {
                return <span>
                    {this.rights[0] ? <a className="a-operate" onClick={me.modify.bind(me, data, index)}>修改</a> : null}
                    {this.rights[0] ? <span className="ant-divider"></span> : null}
                    {this.rights[1] ?
                        <a className="a-operate" onClick={me.setRole.bind(me, data, index)}>分配角色</a> : null}
                    {this.rights[1] ? <span className="ant-divider"></span> : null}
                    {this.rights[2] ?
                        <a className="a-operate" onClick={me.setPwd.bind(me, data, index)}>重置密码</a> : null}
                    {this.rights[2] ? <span className="ant-divider"></span> : null}
                    {this.rights[3] ? <a className="a-operate"
                                         onClick={me.switchStatus.bind(me, data, index)}>{filter.userStatusSwitch(data.userstatus)}</a> : null}
                </span>
            }
        }];
        return {
            Collapse: {
                children: React.createElement(Search, {
                    ref: "search"
                })
            },
            table: {
                columns: columns,
                dataSource: this.state.dataSource,
                loading: this.state.loading,
                pagination: {
                    showSizeChanger: true,
                    showQuickJumper: true,
                    total: me.state.total,
                    pageSizeOptions: ['5', '10', '15', '20', '25'],
                    onShowSizeChange: function (current, pageSize) {
                        console.log(current, pageSize);
                        me.refresh(current, pageSize);
                        me.setState({
                            current: current,
                            pageSize: pageSize
                        });
                    },
                    onChange: function (page) {
                        console.log(page);
                        var pageSize = me.state.pageSize;
                        me.refresh(page, pageSize);
                        me.setState({
                            page: page
                        });
                    }
                }
            }, modal: {
                visible: this.state.visible,
                onOk: function () {
                    console.log(me.state);
                    if (me.state.operation == "modify") {

                        me.refs.userForm.getForm().validateFields((errors, values) => {
                            console.log(errors);
                            if (!!errors) {
                                return;
                            }

                            //var dataSource = me.state.dataSource,
                            //    index = me.state.index,
                            //    key = me.state.key,
                            //    newData = values;
                            //newData.key = key;
                            //newData.userStatus = dataSource[index].userStatus;
                            //dataSource[index] = newData;
                            var modifyParams = values;
                            //modifyParams.orgid = me.state.orgid;

                            var arr = values.orgno.split(",");
                            modifyParams.orgno = arr[0];
                            modifyParams.orgname = arr[1];
                            modifyParams.orgid = arr[2];
                            //usertype只有管理台
                            modifyParams.usertype = "1";

                            modifyParams.userid = me.state.dataSource[me.state.index].userid;
                            //addParams.orgid="01121_";
                            util.httpRequest({
                                type: "POST",
                                url: 'user020103.json',
                                params: modifyParams,
                                success: function (result) {

                                    if (result.ret_code == "0000") {
                                        me.hide();
                                        message.success('修改用户成功！');
                                        me.refresh(me.state.current, me.state.pageSize);
                                    } else {
                                        message.success(result.ret_msg);
                                    }
                                    console.log("result--->", result);

                                }.bind(this)
                            });
                        });
                    }

                },
                onCancel: function () {
                    me.hide();
                },
                title: "修改",
                children: React.createElement(UserForm, {
                    data: this.state.modifyData,
                    options: this.options,
                    key: this.state.randomKey,
                    ref: "userForm"
                })
            },
            addModal: {
                visible: this.state.addVisible,
                onOk: function () {
                    me.refs.addForm.validateFields((errors, values) => {
                        console.log(errors);
                        if (!!errors) {
                            return
                        }
                        //var dataSource = me.state.dataSource,
                        //    index = me.state.index,
                        //    newData = values;
                        //newData.key = parseInt(dataSource[dataSource.length - 1].key) + 1 + "";
                        //newData.userStatus = "F";
                        //
                        //dataSource.push(newData);
                        //var addParams = values;
                        //addParams.orgno = "666666";
                        //addParams.orgid="01121_";
                        var arr = values.orgno.split(",");
                        values.orgno = arr[0];
                        values.orgname = arr[1];
                        values.orgid = arr[2];
                        //usertype只有管理台
                        values.usertype = "1";
                        util.httpRequest({
                            type: "POST",
                            url: 'user020102.json',
                            params: values,
                            success: function (result) {
                                if (result.ret_code == "0000") {
                                    me.hide();
                                    me.refresh(me.state.current, me.state.pageSize);
                                    message.success('添加用户成功!!');
                                }
                            }.bind(this)
                        });

                    });

                },
                onCancel: function () {
                    me.hide();
                },
                title: "添加",
                children: React.createElement(AddForm, {
                    data: this.state.dataSource,
                    ref: "addForm",
                    options: this.options,
                    key: this.state.randomKey
                })
            },
            roleModal: {
                visible: this.state.roleVisible,
                onOk: function () {
                    util.httpRequest({
                        type: "POST",
                        url: 'user020104.json',
                        params: {
                            userid: me.state.userid,
                            roleids: me.state.checkedValues.join(),
                        },
                        success: function (result) {
                            console.log(result);
                            me.hide();
                            if (result.ret_code == "0000") {
                                message.success('修改角色成功！');
                                me.refresh(me.state.current, me.state.pageSize);
                            }
                        }.bind(this)
                    });

                },
                onCancel: function () {
                    me.hide();
                },
                title: "设置用户角色",
                children: React.createElement(SetRole, {
                    userid: this.state.userid,
                    ref: "setRole",
                    roleData: this.state.roleData,
                    roleids: util.getLocalObj("userInfo").roleids,
                    key: this.state.randomKey,
                    onChange: function (checkedValues) {
                        console.log(checkedValues);
                        me.setState({
                            checkedValues: checkedValues
                        })
                    }
                })

            },
            pwdModal: {
                visible: this.state.pwdVisible,
                onOk: function () {
                    me.refs.setPwd.getForm().validateFields((errors, values) => {
                        if (!!errors) {
                            return;
                        }
                        console.log(values);
                        var setPwdparams = values;
                        setPwdparams.userid = me.state.dataSource[me.state.index].userid;
                        util.httpRequest({
                            type: "POST",
                            url: 'user020106.json',
                            params: setPwdparams,
                            success: function (result) {
                                console.log(result);
                                me.hide();
                                message.success('重置密码成功！');
                            }.bind(this)
                        });
                    })
                },
                onCancel: function () {
                    me.hide();
                },
                title: "重置用户密码",
                children: React.createElement(SetPwd, {
                    data: this.state.pwdData,
                    ref: "setPwd"
                })

            },
            btn: {
                children: "+  新增",
                className: "addBtn",
                onClick: function () {
                    me.show("", "", "add");
                }
            },
            exportBtn: {
                children: "导出",
                style: {marginTop: 10, marginBottom: 10},
                onClick: function () {
                    var params = {
                        "globColumn": {
                            "usertype": "用户类型|usertype",
                            "loginname": "登录名称",
                            "username": "用户名称",
                            "userstatus": "用户状态|userstatus",
                            "orgname": "所属机构"
                        },
                        "export_params": {
                            "documentName": "用户列表",
                            "exeid": "M020101EQ003",
                            "type": "xlsx"
                        },
                        "jsondata": {
                            "page": me.state.current,
                            "rows": me.state.pageSize,
                            "user_userid": util.getLocalObj("userInfo").userid,
                            "user_orgno": util.getLocalObj("userInfo").orgno,
                            "username": me.state.searchParams.username,
                            "loginname": me.state.searchParams.loginname,
                            "userstatus": me.state.searchParams.userstatus,
                            "usertype": me.state.searchParams.usertype,
                            "orgno": me.state.searchParams.orgno,
                        }
                    };
                    var paramStr = JSON.stringify(params);
                    var reg = new RegExp("\"", "g");
                    paramStr = paramStr.replace(reg, "'");
                    var t = {};
                    t.paramStr = paramStr;
                    var url = "excelExport.json";
                    // var url =SYS_CONFIG.HOST_URL + SYS_CONFIG.HTTP_ADDRESS sdf + "excelExport.json";234
                    util.exportExcel(url, t);
                }
            }
        }
    }

    show(data, index, operation) {
        console.log(data);
        var me = this;

        if (operation == "modify") {
            this.options = {orgid: data.orgid, orgno: data.orgno, orgname: data.orgname};
            /*2016-12-29-----yh*/
            var dataNew = data;
            dataNew.orgno = dataNew.orgno + "," + dataNew.orgname + "," + dataNew.orgid;
            this.setState({
                    visible: true,
                    index: index,
                    operation: operation,
                    key: data.key,
                    modifyData: dataNew,
                    randomKey: Math.random()

                }
                //    , function () {
                //    var {setFieldsValue} = me.refs.userForm.getForm();
                //    setFieldsValue(data);
                //}
            );
        } else if (operation == "add") {
            this.options = {orgid: me.state.orgid, orgno: me.state.orgno, orgname: me.state.orgname};
            console.log(this.options);

            this.setState({
                addVisible: true,
                index: index,
                operation: operation,
                key: data.key,
                randomKey: Math.random()
            }, function () {
                var {resetFields, setFieldsValue} = me.refs.addForm.getForm();
                resetFields();
                /*2016-12-30-----------------yh*/
                var orgnoTemp = me.state.orgno + "," + me.state.orgname + "," + me.state.orgid;

                setFieldsValue({
                    orgno: orgnoTemp, loginname: ""
                });
            });
        }

    }

    roleShow(data, index) {

        //var ids = util.getLocalObj("userInfo").roleids;
        //console.log("roleids",ids);

        console.log(data);
        var userid = this.state.dataSource[index].userid;
        //获取角色信息
        util.httpRequest({
            type: "POST",
            url: 'user020107.json',
            params: {userid: userid},
            success: function (result) {
                console.log(result);
                if (result.ret_code == "0000") {
                    //设置角色初始值
                    let checkedValues = [];
                    for (let i = 0; i < result.roles_user.length; i++) {
                        checkedValues.push(result.roles_user[i].roleid);
                    }
                    this.setState({
                        roleData: result,
                        randomKey: Math.random(),
                        roleVisible: true,
                        index: index,
                        userid: userid,
                        checkedValues: checkedValues
                    })
                }
            }.bind(this)
        })
    }

    pwdShow(data, index) {
        console.log(data);
        this.setState({
            pwdVisible: true,
            index: index
        }, function () {
            var {resetFields} = this.refs.setPwd.getForm();
            resetFields()
        })
    }

    hide() {
        this.setState({
            visible: false,
            addVisible: false,
            roleVisible: false,
            pwdVisible: false
        })
    }

    onSelect(result, orgStr) {
        console.log(result);
        this.setState({
            dataSource: result.rows,
            orgid: orgStr.split(",")[0],
            orgno: orgStr.split(",")[1],
            orgname: orgStr.split(",")[2]
        })
    }

    onChange(checkedValues) {
        console.log(checkedValues);
        this.setState({
            checkedValues: checkedValues
        })
    }

    search(searchParams) {
        console.log(searchParams);
        searchParams.page = "1";
        searchParams.rows = "10";
        this.searchParams = searchParams;
        if(searchParams.org_no==""){
            searchParams.orgno = util.getLocalObj("userInfo").orgno;
        }else if( searchParams.org_no.split(",").length==3){
            searchParams.orgno = searchParams.org_no.split(",")[0];
        }
        this.setState({
            searchParams: searchParams
        })
        // 搜索用户信息1
        util.httpRequest({
            type: "POST", url: 'user020101.json', params: searchParams, success: function (result) {
                console.log(result);
                this.setState({
                    dataSource: result.rows
                })
            }.bind(this)
        });

    }

    //ewss
    //  {me.state.add ? <Button {...config.btn}></Button> : null}
    render() {
        var config = this.config();
        var me = this;
        const searchConfig = {
            searchTitle: "查询用户",
            searchInit: {
                org_no: ""
            },
            searchField: [[
                {propsname: "用户名称：", propsKey: "username", propsType: "input", key: "1111"},
                {propsname: "登录名称：", propsKey: "loginname", propsType: "input", key: "2222"},

            ], [
                {propsname: "用户状态：", propsKey: "userstatus", propsType: "select", key: "3333"},
                {propsname: "所属机构：", propsKey: "org_no", propsType: "treeselect", key: "4444"}
            ]
            ]
        };
        return (
            <div style={{overflow: "hidden"}}>
                <div>
                    <SearchDemo search={this.search.bind(this)} searchConfig={searchConfig}></SearchDemo>
                    <Modal {...config.modal} closable={false}>
                    </Modal>
                    <Modal {...config.addModal} closable={false}>
                    </Modal>
                    <Modal   {...config.roleModal} closable={false}>
                    </Modal>
                    <Modal {...config.pwdModal} closable={false}>
                    </Modal>

                    <RightButton propsKey="511" btnTxt="+  新增" styleName="addBtn"
                                 oprate={this.show.bind(this, "", "", "add")}> </RightButton>
                    <Button {...config.exportBtn}></Button>
                    <Table {...config.table}/>
                </div>


            </div>
        );
    }
}
export default User;
